package br.com.intelsys.basics.spring.validator;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;

public class IValidatorException extends Exception {
	public static final String ERROR_LIST = "errorList";
	public static final String ERROR_PARAM_LIST = "errorParamList";
	private static final long serialVersionUID = 9190767959133725836L;
	private List<String> errorList = new ArrayList<String>();
	private List<String[]> paramErrorList = new ArrayList<String[]>();
	private Object entity;
	private static final Logger log = Logger.getLogger(IValidatorException.class);

	public IValidatorException(Throwable e) {
		super(e);
	}

	public IValidatorException() {
	}

	public IValidatorException(List<String> errorList, List<String[]> paramList) {
		this.errorList = errorList;
		this.paramErrorList = paramList;
	}

	public IValidatorException(String error, String... param) {
		errorList.add(error);
		paramErrorList.add(param);
	}

	public boolean isClean() {
		return !hasError();
	}

	public boolean hasError() {
		return errorList != null && errorList.size() > 0;
	}

	public boolean hasError(String error) {
		return errorList != null && errorList.contains(error);
	}

	public boolean hasError(String error, String param) {
		if (hasError(error)) {
			int i = 0;
			for (String err : errorList) {
				if (error.equals(err)) {
					String[] paramErrorArr = paramErrorList.get(i);
					if (paramErrorArr != null) {
						for (String paramTmp : paramErrorArr) {
							if (param.equals(paramTmp)) {
								return true;
							}
						}
					}
				}
				i++;
			}
		}
		return false;
	}

	public boolean hasErrorOnParam(String param) {
		return errorList != null && paramErrorList != null && paramErrorList.contains(param);
	}

	public List<String> getErrorList() {
		if (log.isDebugEnabled()) {
			if (errorList != null) {
				int index = 0;
				for (String error : errorList) {
					log.debug("ERROR LIST [" + index + "]: " + error);
					if (paramErrorList != null && paramErrorList.get(index) != null) {
						int j = 0;
						for (String param : paramErrorList.get(index)) {
							log.debug("ERROR PARAM LIST [" + j++ + "]: " + param);
						}
					}
					index++;
				}
			}
		}
		return errorList;
	}

	public List<String[]> getParamErrorList() {
		return paramErrorList;
	}

	public IValidatorException addError(String error, String... param) {
		errorList.add(error);
		paramErrorList.add(param);
		return this;
	}

	public ModelAndView getModelAndView(String viewName) {
		return new ModelAndView(viewName).addObject(ERROR_LIST, getErrorList()).addObject(ERROR_PARAM_LIST, getErrorList());
	}

	public void setEntity(Object entity) {
		this.entity = entity;
	}

	public Object getEntity() {
		return entity;
	}
}
